<template>
  <div class="upload-excel">
    <div class="uploabtn" style="display:flex;justify-content:space-between">
        <div style="display:flex;align-items:center">
            <el-upload
                ref="upload"
                style="margin: 10px"
                class="upload-demo"
                :action="uploadUrl"
                :headers="headers"
                :data="params"
                :on-change="handleChange"
                :before-upload="beforeUpload"
                :on-success="handleSuccess"
                :on-error="onError"
                multiple
                :auto-upload="false"
                :show-file-list="false"
                :file-list="params.formFile"
                :limit="1"
                :on-exceed="uploadExceed"
            >
                <el-button size="small" type="primary" class="uploaddemo"
                >上传文件</el-button
                >
            </el-upload>
            <el-button class="download" type="success" @click="downloadTemp"  style="margin-left:10px">下载模板</el-button>
            <!-- <el-button class="download" type="warning" @click="downloadTemp">导出</el-button> -->
            <download-excel
            class = "export-excel-wrapper"
            :data = "json_data"
            :fields = "json_fields"
            name = "账单核销结果.xls">
                <!-- 上面可以自定义自己的样式，还可以引用其他组件button -->
                <el-button :disabled='json_data&&json_data.length<=0'  class="download" type="warning" style="margin-left:10px">导出</el-button>
                <!-- <el-button :disabled='checkList&&checkList.length<=0'  class="download" type="warning" style="margin-left:10px">导出</el-button> -->
            </download-excel>
            <div slot="tip" class="el-upload__tip" style="margin-left:10px">只能上传单个Excel文件，且不超过50M</div>
        </div>

      <el-button class="download" type="danger" style="margin-left:10px" @click="handleSelectionChange">一键复核</el-button>
    </div>
    <el-table :data="checkList" style="width: 100%" border >
        <!-- <el-table-column type="selection" width="60" align="center"></el-table-column> -->
        <el-table-column label="运单编号" prop="logisticCode"></el-table-column>
        <el-table-column label="对比结果" prop="result"></el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="150">
            <template slot-scope="{ row }">
            <el-button type="success" size="mini" @click="handleSeeOrder(row)">复核</el-button>
            </template>
        </el-table-column>
    </el-table>
  </div>
</template>

<script>
/*上传控件：有上传有文件列表 */
// import {apifileDelete,apiDownLoad } from "../api/api";templateExpressExport
import { adminVerfify ,templateVerifyExport,reviewVerify} from "@/api/shipments";
import { parseTime,English } from "@/utils";
import * as http from "../../main";

export default {
  props: {
    params: {
      type: Object,
    },
  },
  data() {
    return {
      checkList: [
      ],
      isConfirm: true,
      uploadUrl: http.base + "/file/upload/excel", //上传路径
      headers: {}, //上传请求头部
      json_fields: {
        "运单编号": "logisticCode",    //常规字段
        "对比结果": "result", //支持嵌套属性
      },
      json_data: [],
      json_meta: [
        [
          {
            " key ": " charset ",
            " value ": " utf- 8 "
          }
        ]
      ]
    };
  },
  methods: {
    //   单个复核
      handleSeeOrder(val){
          console.log(val)
          let datas = [val.logisticCode]
          this.fuhever(datas)
      },
    //   全部复核
      handleSelectionChange(){
          let datalist =[];
          datalist.push(this.checkList.map((val,index)=>{
              console.log(val.logisticCode)
              return val.logisticCode
          }))
          this.fuhever(datalist[0])

      },
      // 复核接口
      fuhever(datas){
        reviewVerify(datas).then(res =>{
        console.log(res)
        if(res.success){
            this.$message({
                message:"复核成功",
                type:'success'
            });
        }else{
            this.$message.error(res.msg);
        }
        })
      },
    //   文件超出个数限制时的钩子
      uploadExceed(files, fileList) {
          if(fileList.length>0){
            this.$set(fileList[0], 'raw', files[0]);
            this.$set(fileList[0], 'name', files[0].name);
            this.$refs['upload'].clearFiles();//清除文件
            this.$refs['upload'].handleStart(files[0]);//选择文件后的赋值方法
          }
      },
    async handleChange(files, fileList) {
      if (!this.isConfirm) {
        this.isConfirm = true;
        return;
      }
      const bo = await this.$confirm("上传文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "info",
      })
        .then(() => {
        //   console.log("确定上传");
        //   console.log('确定files, fileList: ', files, fileList);
          return true;
        })
        .catch(() => {
        //   console.log("取消上传");
        //   console.log('取消files, fileList: ', files, fileList);
          return false;
        });
      if (bo) {
        this.params.formFile = fileList;
        this.$refs.upload.submit();
        this.isConfirm = false;
      } else {
        this.$refs.upload.clearFiles();
        this.params.formFile = [];
      }
    },
    handleSuccess(response, file, fileList) {
      const FName = response.data;
      let that = this;
      console.log(that.checkList)
      //重新获取文件列表
      let query = {
        filename: FName,
      };
      adminVerfify(query).then((res) => {
            console.log(that.checkList)
          if (res.success) {
            that.checkList = res.data;
            that.json_data = res.data;
            this.$message({
                message:res.msg,
                type:'success'
            });
            console.log(that.checkList)
          } 
          else if(!res.success && res.data == null){
            this.$message.error(res.msg);
          }
        })
        .catch(() => {});
    },
    //上传之前
    beforeUpload(file) {
      // 对文件类型进行判断
      let extension1 =
        file.name.substring(file.name.lastIndexOf(".") + 1) === "xls";
      let extension2 =
        file.name.substring(file.name.lastIndexOf(".") + 1) === "xlsx";
      let size = file.size / 1024 / 1024 < 50;
    //   console.log("extension1 extension2 size");
    //   console.log(extension1, extension2, size);
      if (!extension1 && !extension2) {
        // console.log("!extension1 && !extension2: ", !extension1 && !extension2);
        this.$message.error("只能上传后缀是.xls或者.xlsx的文件!");
        return false;
      }
      if (!size) {
        this.$message.error("文件大小不得超过50M");
        return false;
      }
      return ;
    },
    //  上传失败
    onError(err, file, fileList){
        let errMsg=err.toString().replace('Error:','')
        errMsg=JSON.parse(errMsg)
        // console.log('errMsg11111: ', errMsg);
        this.$message.error(errMsg.msg)
    },
    // 下载文件模板
    downloadTemp(){
            return new Promise(() => {
            templateVerifyExport().then(async (res) => {
                console.log("导出结果", res);
                var blob = new Blob([res], {
                type:
                    "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8",
                });
                //创建一个a标签
                var oA = document.createElement("a");
                oA.href = window.URL.createObjectURL(blob);
                // 给文件命名
                oA.download = `核销检验模板文件_${parseTime(
                new Date(),
                "{y}{m}{d}{h}{i}{s}"
                )}.xls`;
                // 模拟点击
                oA.click();
                window.URL.revokeObjectURL(blob); // 释放掉blob对象
                // that.exportloading = false;
            });
            });
        //  }else{
        //     this.$message.warning('请选择单位');
        // }
    },
  },
  created() {
    this.headers = {
      Authorization: "Bearer " + (this.$store.getters.token || ""),
    };
  },
};
</script>

<style scoped lang='scss'>
.upload-excel {
  .el-table {
    margin-top: 10px;
  }
  .uploabtn {
    display: flex;
    align-items: center;
  }
  .download{
    // margin-right: 10px;
    padding: 0;
    width: 80px;
    height: 32px;
    font-size: 12px;
  }
}
.excel-upload-input {
  display: none;
  z-index: -9999;
}
.drop {
  border: 2px dashed #bbb;
  width: 50%;
  height: 50%;
  line-height: 160px;
  margin: 0 auto;
  font-size: 24px;
  border-radius: 5px;
  text-align: center;
  color: #bbb;
  /* position: relative; */
}
</style>